#!/usr/bin/perl
#sysinfos-lib.pl

do "../web-lib.pl";
&init_config();
%access = get_module_acl();

if ($gconfig{'real_os_type'}) { $ostr = "$gconfig{'real_os_type'} $gconfig{'real_os_version'}"; }
else { $ostr = "$gconfig{'os_type'} $gconfig{'os_version'}"; }

sub percent_box {
	my($percent,$yellow,$red)=@_;
	if ($m_percent < $yellow) {
		$image=$config{'green'} ;
	}
	elsif ($m_percent < $red ) {
		$image=$config{'yellow'} ;
	}
	else {
		$image=$config{'red'} ;
	}
	return "<table border=0 width=250><tr><td width=* bgcolor='#C0C0C0'><IMG SRC=".$image." ALIGN=left height=6 WIDTH=".$percent."%> </td></tr></table>";
	
}
sub format_bytesize() {
    $kbytes=$_[0]/1024;
    if ($kbytes > 1048576) { $result = sprintf("%.2f", $kbytes/1048576) . " GB"; }
    elsif ($kbytes > 1024) { $result = sprintf("%.2f", $kbytes/1024) . " MB"; }
    else { $result = sprintf("%.2f", $kbytes) . " KB"; }
    return $result;
}

sub gethostname() {
	if ($ostr =~ /BSD/) { open (FIC, "hostname|"); }
	else { open (FIC, "</proc/sys/kernel/hostname"); }
    @hostname=<FIC>;
    close(FIC);
	$name = $hostname[0];#." (" . (split /address/, `host $hostname[0]`)[1] .")";
    return $name;
}

sub getUptime() {
	if ($ostr =~ /BSD/) {
		open (FIC,"uptime|");
		@uptime=<FIC>;
		close(FIC);
		$time_load = (split /up/, $uptime[0])[1] ;
		$result = (split /\,/, $time_load)[0].(split /\,/, $time_load)[1]." hours" ;
	}
	else {
		open (FIC,"</proc/uptime");
		@uptime=<FIC>;
	    close(FIC);
	    $min=(split / /, $uptime[0])[0]/60;
	    $hours=$min/60;
	    $days=int($hours/24);
	    $hours=int($hours - ($days*24));
	    $min=int($min - ($days*60*24) - ($hours*60));

	    if ($days != 0) { $result = "$days days, "; }
	    if ($hours != 0) { $result .= "$hours hours, "; }
	    $result .= "$min minutes";
	}
    return $result;
}

sub getLoadAvg() {
	if ($ostr =~ /BSD/) { open (FIC, "sysctl -n vm.loadavg|"); $cpt=1; }
	else { open (FIC, "</proc/loadavg"); $cpt=0; }
	@loadavg=<FIC>;
	@load = split /\s+/, $loadavg[0] ;
    close(FIC);
	return "$load[$cpt++] (1 min), $load[$cpt++] (5 min), $load[$cpt] (15 min)";
}

sub getMatos() {
	if ($ostr =~ /BSD/) {
		$matos[0] = `sysctl -n hw.ncpu` ;
		$matos[1] = `sysctl -n hw.model` ;
        $cpu_line = `grep CPU: /var/run/dmesg.boot` ;
        $cpu_line =~ s/CPU: (.*) \((.*)-MHz (.*)\)/$2/ ;

        $matos[2] = $cpu_line ;
	}
	else {
	    open (FIC, "</proc/cpuinfo");
	    while (<FIC>) {
			my $fcol = (split /:/)[0];
			if ( $fcol =~ /processor/) { $matos[0] = (split /:/)[1] + 1; }
			elsif ( $fcol =~ /ncpus probed/) { $matos[0] = (split /:/)[1]." ".$text{'mat_proc_probed'}; }
			elsif ( $fcol =~ /ncpus active/) { $matos[0] .= " / ".(split /:/)[1]." ".$text{'mat_proc_active'}; }
			elsif( $fcol =~ /cpus detected/) { $matos[0] = (split /:/)[1]; }
			elsif ( $fcol =~ /model name/) { $matos[1] = (split /:/)[1]; }
			elsif( $fcol =~ /^cpu\s*$/) { $matos[1] .= (split /:/)[1]; }
			elsif ( $fcol =~ /cpu model/) { $matos[1] .= " " . (split /:/)[1]; }
			elsif ( $fcol =~ /platform string/) { $matos[1] .= " (" . (split /:/)[1] . ")"; }
			elsif ( $fcol =~ /cpu MHz/) { $matos[2] = (split /:/)[1]; }
			elsif ( $fcol =~ /cycle frequency \[Hz\]/) { $matos[2] = (split /:/)[1] /1000000; }
			elsif ( $fcol =~ /cache size/) { $matos[3] = (split /:/)[1]; }
			elsif ( $fcol =~ /bogomips/i) { $matos[4] += (split /:/)[1]; }
	    }
    	close(FIC);
	}
	    return @matos;
}

sub getPCI() {
	if ($ostr =~ /BSD/) {
		open (FIC, "</var/run/dmesg.boot") ;
		@dmesg = <FIC> ;
		close (FIC);
		$count = 0 ;
		@results = () ;
		for ($i=0; $i<$#dmesg; $i++) {
			if ($dmesg[$i] =~ /(.*): <(.*)>.* at [.0-9]+ irq/) { $results[$count++] = $1.": ".$2 ; }
		}
		return @results ;
	}
	else {
	    open (FIC, "</proc/pci");
	    $cpt=0;
	    while (<FIC>) {
	        if (/^\s*Bus/) {
	            $device=1;
	            next;
	        }
	        if ($device) {
	            if ( ($_ =~ /bridge/) && !($_ =~ /USB/) ) {
	                $PCI[$cpt++] = (split /:/)[1];
	            }
	            $device=0;
	        }
	    }
	    close (FIC);
	    return @PCI;
	}
}

sub getAutresPCI() {
	if ($ostr =~ /BSD/) {
		open (FIC, "</var/run/dmesg.boot") ;
		@dmesg = <FIC> ;
		close (FIC);
		$count = 0 ;

		@results = () ;
		for ($i=0; $i<$#dmesg; $i++) {
			if ($dmesg[$i] =~ /(.*): <(.*)>(.*) pci[0-9]$/) { $results[$count++] = $1.": ".$2 ; }
		}
		return @results ;
	}
	else {
		open (FIC, "</proc/pci");
		$cpt=0;
		while (<FIC>) {
			if (/^\s*Bus/) {
				$device=1;
				next;
			}
			if ($device) {
				if (!($_ =~ /bridge/)) { $PCI[$cpt++] = (split /:/)[1]; }
				$device=0;
			}
		}
		close (FIC);
		return @PCI;
	}
}

sub getIDE() {
	if ($ostr =~ /BSD/) {
		open (FIC, "</var/run/dmesg.boot") ;
		@dmesg = <FIC> ;
		close (FIC);
		$count = 0 ;
		@results = () ;
		for ($i=0; $i<$#dmesg; $i++) {
			if ($dmesg[$i] =~ /^(ad[0-9]): (.*)MB <(.*)> (.*) (.*)/) { $results[$count++] = $1.": ".$2."MB ".$3 ; }
			if ($dmesg[$i] =~ /^(acd[0-9]): (.*) <(.*)> (.*)/) { $results[$count++] = $1.": ".$2." ".$3 ; }
		}
        return @results ;
	}
	else {
			$cpt=0;
			opendir(REP,"/proc/ide");
			while ($file=readdir(REP)) {
				chomp($file);
				if ($file =~ /^hd/) {
					$IDE[$cpt]="$file :";
					open (FIC, "</proc/ide/$file/model");
					@temp=<FIC>;
					close(FIC);
					chomp($temp[0]);
					$IDE[$cpt].=" $temp[0]";
					open (FIC, "</proc/ide/$file/capacity");
					@temp=<FIC>;
					close(FIC);
					chomp($temp[0]);
					$temp[0] /= 2 ;
					$temp[0] *= 1024;
					$IDE[$cpt].=" (".&format_bytesize($temp[0]).")";
					$cpt++;
				}
			}
			closedir(REP);
			return @IDE;
    }
}

sub getSCSI() {
	if ($ostr =~ /BSD/) {
		open (FIC, "</var/run/dmesg.boot") ;
		@dmesg = <FIC> ;
		close (FIC);
		$count = 0 ;
		@results = () ;
		for ($i=0; $i<$#dmesg; $i++) {
			if ($dmesg[$i] =~ /^(.*): <(.*)> .*SCSI.*device/) { $results[$count++] = $1.": ".$2 ; }
		}
		return @results ;
	}
	else {
			open (FIC, "</proc/scsi/scsi");
			$cpt=0;
			while (<FIC>) {
				if (/Vendor:\s+(.*)\s+Model:\s+(.*)\s+Rev:\s+(.*)/i) {
					$SCSI[$cpt]="$1 $2";
					$get_type=1;
					next;
				}
				if ($get_type && /Type:\s+(\S+)/i) {
					$SCSI[$cpt].=" ($1)";
					$cpt++;
					$get_type=0;
				}
			}
			close (FIC);
			return @SCSI;
	}
}

sub getMemInfo() {
	if ($ostr =~ /BSD/) {
		$ram_total = `sysctl -n hw.physmem` ;
        $page_size = `sysctl -n hw.pagesize` ;
        @vmstat = `vmstat` ;
        $ram_free = (split /\s+/,$vmstat[2])[5] ;
        $ram_free *= $page_size ;
        $ram_used = $ram_total - $ram_free ;
        $ram_percent = int( ($ram_used/$ram_total) * 100) ;
        $MEM[0] = "$ram_percent $ram_free $ram_used $ram_total" ;
        @swapinfo = `swapinfo -k` ;
        ($swap_disk, $swap_total, $swap_used, $swap_free, $swap_percent, $swap_type) = split /\s+/, $swapinfo[1] ;
        $swap_used *= 1024 ;
        $swap_total *= 1024 ;
        $swap_free *=1024 ;
        $swap_percent =~ s/\%// ;
        $MEM[1] = "$swap_percent $swap_free $swap_used $swap_total" ;
	}
    open (FIC, "</proc/meminfo");
    while (<FIC>) {
        if (/Mem:/) {
            ($total,$used,$free,$shared,$buffers,$cached) = (split /\s+/)[1..6];
	    $used=$used-$buffers-$cached;
	    $free=$total-$used;
            $MEM[0]=int($used *100/$total) . " $free $used $total";
        }
        elsif (/Swap:/) {
            ($total,$used,$free) = (split /\s+/)[1..3];
            $MEM[1]=int($used *100/$total) . " $free $used $total" if ($total > 0);
        }
    }
    return @MEM;
}

sub SystemTable() {
print "<TR class=title1> <th colspan=2> $text{'system_title'} </th> </TR>\n";
printf "<TR class=mode1> <TD><b> $text{'system_id'} : </b></TD> <TD> %s </TD> </TR>\n",  (&get_sid()) ?  &get_sid(): $text{'no_systemid'};
print "<TR class=mode2> <TD><b> $text{'system_host'} : </b></TD> <TD>". &gethostname() ."</TD> </TR>\n";
#print "<TR> <TD BGCOLOR=\"#DDDDDD\" ALIGN=RIGHT> $text{'system_OS'} : </TD> <TD> ". &getOStype() . " ". &getOSrelease() ."</TD> </TR>\n";
print "<TR class=mode1> <TD><b> $text{'system_uptime'} : </b></TD> <TD> ". &getUptime() ."</TD> </TR>\n";
print "<TR class=mode2> <TD><b> $text{'system_loadavg'} : </b></TD> <TD> ". &getLoadAvg() ."</TD> </TR>\n";
}

sub MoniterTable() {
my @entry = get_sysmon();
my %elem;
foreach my $i (@entry)
{
	my($key, $value) = split(':', $i);
	$elem{$key} = $value;
}
print "<TR class=title1><th colspan=2><B>$text{'sysmon'}</B></th></TR>\n";
print "<tr class=mode1><td><b>CPU0 Temp</b></td><td>";
if($elem{'CPU0'}){
	print $elem{"CPU0"}." C";
}
print "</td></tr>\n";
print "<tr class=mode2><td><b>CPU1 Temp</b></td><td>";
if($elem{'CPU1'}){
        print $elem{"CPU"}." C";
}
print "</td></tr>\n";
print "<tr class=mode1><td><b>Chip Temp</b></td><td>";
if($elem{'DDR'}){
	print $elem{"DDR"}." C";
}
print "</td></tr>\n";
print "<tr class=mode2><td><b>CPU Voltage</b></td><td>";
if($elem{'CPU_Voltage'}){
	print $elem{"CPU_Voltage"}." V";
}
print "</td></tr>\n";
print "<tr class=mode1><td><b>5V Voltage</b></td><td>";
if($elem{'5V_StandBy'}){
	print $elem{"5V_StandBy"}." V";
}
print "</td></tr>\n";
#print "<tr class=mode1><td><b>cpu tmp</b></td><td></td></tr>\n";
#print "<tr class=mode1><td><b>cpu tmp</b></td><td></td></tr>\n";
}  #end of MoniterTable()

sub MaterialTable() {
print "<TR class=title1> <th colspan=2> <B>$text{'mat_title'}</B> </th> </TR>\n";
@matos=&getMatos();
print "<TR class=mode1> <TD><b> $text{'mat_proc'} : </b></TD> <TD>". $matos[0] ." </TD> </TR>\n";
print "<TR class=mode2> <TD><b> $text{'mat_modele'} : </b></TD> <TD>". $matos[1] ." </TD> </TR>\n";
print "<TR class=mode1> <TD><b> $text{'mat_freq'} : </b></TD> <TD>". $matos[2] ." Mhz</TD> </TR>\n";
print "<TR class=mode2> <TD><b> $text{'mat_cache'} : </b></TD> <TD>". $matos[3] ." </TD> </TR>\n";
print "<TR class=mode1> <TD><b> $text{'mat_bogomips'} : </b></TD> <TD>". $matos[4] ." </TD> </TR>\n";
#print "<TR class=mode1> <TD ALIGN=RIGHT COLSPAN=2> &nbsp; </TD> </TR>\n";
@PCI=&getPCI();
print "<TR class=mode2> <TD><b>$text{'mat_PCI'} : </b></TD> <TD>\n";
foreach (@PCI) {
    chomp();
    $_=~s/^\s+//;
    $_=~s/\s+$//;
    print $_."<BR>\n";
}
print "</TD> </TR>\n";
@PCI = () ;
@PCI=&getAutresPCI();
print "<TR class=mode1> <TD><b>$text{'mat_oPCI'} : </b></TD> <TD>\n";
foreach (@PCI) {
    chomp();
    $_=~s/^\s+//;
    $_=~s/\s+$//;
    if(!($_ =~ /^PCI\sdevice/)){
    	print $_."<BR>\n";
    }
}
print "</TD> </TR>\n";
@IDE=&getIDE();
print "<TR class=mode2> <TD><b>$text{'mat_IDE'} : </b></TD> <TD>\n";
foreach (sort { $a cmp $b} @IDE) {
    chomp();
    $_=~s/^\s+//;
    $_=~s/\s+$//;
    print $_."<BR>\n";
}
print "</TD> </TR>\n";
@SCSI=&getSCSI();
print "<TR class=mode1> <TD><b>$text{'mat_SCSI'} : </b></TD> <TD>\n";
foreach (sort { $a cmp $b} @SCSI) {
    chomp();
    $_=~s/^\s+//;
    $_=~s/\s+$//;
    print $_."<BR>\n";
}
print "</TD> </TR>\n";

print "</TD> </TR>\n";
}

sub MemTable() {
#@MEM=&getMemInfo();
($m_percent,$m_free,$m_used,$m_total) = split / /, $MEM[0];
($s_percent,$s_free,$s_used,$s_total) = split / /, $MEM[1] if(@MEM == 2);
@vmstat = `vmstat` ;
open(ME, "/proc/meminfo");
@mi = <ME>;
close(ME);
if($mi[0] =~ /^MemTotal:\s+(\d+).*/)
{
  $mtotal = $1;
  $mtotal = int($mtotal / 1024);
}
$ram_free = (split /\s+/,$vmstat[2])[4] ;
$ram_buff = (split /\s+/,$vmstat[2])[5] ;
$ram_cache = (split /\s+/,$vmstat[2])[6] ;
#--------------free-----------#
open(FREE, "free|");
@free=<FREE>;
close(FREE);
if($free[1]=~ /Mem:\s+(\d+)\s+/){
	$memt=$1;
#	$memt = 4096 * 1024;
	$memt=int($memt /1024);
}
if($free[2]=~ /-\/\+\sbuffers\/cache:\s+(\d+)\s+(\d+)\s+/){
	$memused = $1;
	$memused = int($memused / 1024);
}
#$ramfree = ($ram_free + $ram_buff + $ram_cache) / 1024;
$ramfree = $ram_free / 1024;
$m_percent = int(($mtotal - int($ramfree)) * 100 / $mtotal);
$mpercent = int($memused * 100 / $memt);
print "<TR class=title1> <th colspan=2 > $text{'mem_title'} </th> </TR>\n";
print "<TR class=mode1>";
print "<TD> <B>$text{'mem_total'}:</B> </TD>\n";
print "<TD>$memt MB</TD>";
#print "<TD>". &format_bytesize($m_total) ." </TD>";
print "</TR>\n";
print "<TR class=mode2>";
print "<TD><B>$text{'mem_util'}:($mpercent%) </B></TD>";
#print "<TD>". $m_percent. "</TD>";
print "<TD>".&percent_box($mpercent,$config{'yellow_limit'},$config{'red_limit'})."</TD>";
print "</TR>\n";

if (@MEM == 2)
{
	print "<TR class=mode1>";
	print "<TD> <B>$text{'mem_swap'} :</B> </TD>";
	print "<TD>". &format_bytesize($s_total) ." </TD>";
	print "</TR>\n";
	print "<TR class=mode2>";
	print "<TD><B>$text{'mem_util'}:($s_percent%) </B></TD>";
	print "<TD>".&percent_box($s_percent,$config{'yellow_limit'},$config{'red_limit'})."</TD>";
	print "</TR>\n";
}

}

#get_sid(void)
#return system id
sub get_sid()
{
         my ($sid, @file, $i);
	 
	 $sid = "";

	 open(SYSTEMID, $config{'systemid'});
	 @file = <SYSTEMID>;
	 close(SYSTEMID);

	 for($i = 0; $i < @file; $i++)
	 {
	         chomp($file[$i]);
		 if($file[$i])
		 {
		         $sid = $file[$i];
		         last;
		 }
	 }

	 return $sid;
}

sub get_sysmon()
{
        open(FH, "/usr/bin/sensors |");
        @sen = <FH>;
        close(FH);
        my $sysmon;
        for($i=0; $i<@sen; $i++) {
                $sen[$i] =~ s/\r|\n//g;
                $sen[$i] =~ s/\*|\t//g;
                if($sen[$i] =~ /(\+3\.3V:)\s+(\S+)\sV/){
                        push(@sysmon, $1.$2);
                }
                elsif($sen[$i] =~ /(5V StandBy:)/) {
                        if($sen[$i+1] =~ /\s+(\S+)\sV/){
                                push(@sysmon,"5V_StandBy:".$1);
                        }
                }
                elsif($sen[$i] =~ /(CPU Voltage:)/){
                        if($sen[$i+1] =~ /\s+(\S+)\sV/){
                                push(@sysmon,"CPU_Voltage:".$1);
                        }
                }
                elsif($sen[$i] =~ /(\+5V:)\s+(\S+)\sV/){
                        push(@sysmon,$1.$2);
                }
                elsif($sen[$i] =~ /(\+12V:)\s+(\S+)\sV/){
                        push(@sysmon,$1.$2);
                }
                elsif($sen[$i] =~ /(-12V:)\s+(\S+)\sV/){
                        push(@sysmon,$1.$2);
                }
                elsif($sen[$i] =~ /(Vdd:)\s+(\S+)\sV/){
                        push(@sysmon,$1.$2);
                }
                elsif($sen[$i] =~ /(Vbat:)\s+(\S+)\sV/){
                        push(@sysmon,$1.$2);
                }
                elsif($sen[$i] =~ /(Vsb:)\s+(\S+)\sV/){
                        push(@sysmon,$1.$2);
                }
                elsif($sen[$i] =~ /(AVdd:)\s+(\S+)\sV/){
                        push(@sysmon,$1.$2);
                }
                elsif($sen[$i] =~ /(CPU0 Temp:)\s*(\+\d+\.*\d*)/){
                        push(@sysmon,"CPU0:".$2);
                }
                elsif($sen[$i] =~ /(CPU1 Temp:)\s*(\+\d+\.*\d*)/){
                        push(@sysmon,"CPU:".$2);
                }
                elsif($sen[$i] =~ /(S-IO Temp:)\s*(\+\d+\.*\d*)/){
                        push(@sysmon,"S-IO:".$2);
                }
                elsif($sen[$i] =~ /(DDR Temp:)\s*(\+\d+\.*\d*)/){
                        push(@sysmon,"DDR:".$2);
                }
        }
        return @sysmon;

}
1;
